package cn.leven.dao.impl;

import cn.leven.dao.UserDao;
import cn.leven.domain.User;
import cn.leven.domain.UserInfo;
import cn.leven.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {
    private  JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<UserInfo> findAll() {
        // 使用jsbc操作数据库
        String sql = "select * from user";
        List<UserInfo> users = template.query(sql,new BeanPropertyRowMapper<UserInfo>(UserInfo.class));
        return users;
    }

    @Override
    public UserInfo findUser(String username, String password) {
       try {
           String sql = "select * from  user where username = ? and password = ?";
           UserInfo user = template.queryForObject(sql,
                   new BeanPropertyRowMapper<UserInfo>(UserInfo.class),
                   username,password);
           return user;
       }catch (Exception e){
           e.printStackTrace();
           return  null;
       }
    }

    @Override
    public void addUser(UserInfo userInfo) {
        try {
            String sql = "insert into user values (null,?,?,?,?,?,?,null,null)";
            template.update(sql, userInfo.getName(),userInfo.getGender(),userInfo.getAge(),userInfo.getAddress(),userInfo.getQq(),userInfo.getEmail());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void deleteUser(Integer id) {
        try {
            String sql = "delete from user where id = ?";
            template.update(sql, id);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public UserInfo findUser(int id) {
        try {
            String sql = "select * from  user where id = ?";
            UserInfo user = template.queryForObject(sql,
                    new BeanPropertyRowMapper<UserInfo>(UserInfo.class),
                    id);
            return user;
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
    }

    @Override
    public void updateUser(UserInfo userInfo) {
        try {
            String sql = "update user set name = ?, gender=?,age=?,address=?,qq=?,email=? where id=?";
            template.update(sql, userInfo.getName(),userInfo.getGender(),userInfo.getAge(),userInfo.getAddress(),userInfo.getQq(),userInfo.getEmail(),userInfo.getId());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
